package cn.achao.csr.chat.controller;

import cn.achao.csr.api.SequenceApi;
import cn.achao.csr.api.model.req.ChatMessagePageReq;
import cn.achao.csr.api.model.req.ChatMessageReq;
import cn.achao.csr.api.model.resp.ChatMessageResp;
import cn.achao.csr.base.constant.SecurityConstants;
import cn.achao.csr.base.resp.CursorPageBaseResp;
import cn.achao.csr.base.resp.R;
import cn.achao.csr.chat.service.ChatService;
import cn.achao.csr.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @Author: achao
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/chat")
public class ChatController {

    private final ChatService chatService;
    private final SequenceApi sequenceApi;

    /**
     * 获取游客编码
     * @return
     */
    @GetMapping("/getTouristsCode")
    public R<Long> getTouristsCode() {
        Long touristsCode = sequenceApi.getSegmentId("seq_chat_tourists_code", SecurityConstants.INNER);
        touristsCode = Long.valueOf("9" + touristsCode);
        return R.ok(touristsCode);
    }

    /**
     * 获取会话消息分页
     * @param req
     * @return
     */
    @GetMapping("/msg/page")
    public R<CursorPageBaseResp<ChatMessageResp>> getMsgPage(@Valid ChatMessagePageReq req) {
        Long userId = SecurityUtils.getUserId();
        CursorPageBaseResp<ChatMessageResp> msgPage = chatService.getMsgPage(req, userId);
        // TODO 过滤黑名单消息
        return R.ok(msgPage);
    }

    /**
     * 发送消息
     * @param req
     * @return
     */
    @PostMapping("/senMsg")
    public R<ChatMessageResp> senMsg(@Valid @RequestBody ChatMessageReq req) {
        Long userId = SecurityUtils.getUserId();
        Long msgId = chatService.sendMsg(req, userId);
        ChatMessageResp msgResp = chatService.getMsgResp(msgId, userId);
        return R.ok(msgResp);
    }

}
